package com.etc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class JdbcUtil {
	
	private static String url = "jdbc:mysql://localhost:3306/test?“?useUnicode=true&characterEncoding=utf8";
	private static String user = "root";
	private static String pwd = "root";
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConn(){
		try {
			return DriverManager.getConnection(url, user, pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void closeAll(ResultSet rs, Statement ps, Connection conn){
		
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps != null){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public static ResultSet doQuery(Connection conn,String sql,Object...params){
		ResultSet rs = null;
		try {
			PreparedStatement pstm=conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pstm.setObject(i+1, params[i]);
				}
			}
			rs=pstm.executeQuery();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	public static int doUpate (Connection conn,String sql,Object...params) throws SQLException{
		PreparedStatement ps=conn.prepareStatement(sql);
		if(params!=null){
			for(int i=0;i<params.length;i++){
				ps.setObject(i+1, params[i]);
			}
		}
		int result=ps.executeUpdate();
		return result;
	}
	
	
	
	
	
}
